package com.warmlight.voicepacket.widget;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.FloatPlayListDetailAdapter;
import com.warmlight.voicepacket.data.UserCoverDetailData;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.dbdata.DBFloatPlayListDetail;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by jason on 2018/5/26.
 */

public class FloatPlayListDetail extends RelativeLayout {

    private DBFloatPlaylist mData;
    private Context mContext;
    private RelativeLayout mContainer;
    private List<DBFloatPlayListDetail> mList;
    private ListView lv_playlist_detail;
    private FloatPlayListDetailAdapter mAdapter;

    public FloatPlayListDetail(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public FloatPlayListDetail(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public FloatPlayListDetail(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public FloatPlayListDetail(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext = context;
        init();
    }

    public FloatPlayListDetail(Context context, DBFloatPlaylist data){
        super(context);
        mData = data;
        mContext = context;
        init();
    }

    private void init(){
        mContainer = (RelativeLayout) View.inflate(mContext, R.layout.float_playlist_detail, this);
        lv_playlist_detail =(ListView) mContainer.findViewById(R.id.lv_playlist_detail);
        mList = new ArrayList<>();
        mAdapter = new FloatPlayListDetailAdapter(mContext, mList);
        lv_playlist_detail.setAdapter(mAdapter);

        lv_playlist_detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                EventBus.getDefault().post(new PlayerServiceData(PlayerServiceData.PLAY, mList.get(i).getAudio_url(),"delay",true));

                //
                ClickLog.clickLog(ClickLog.float_clot_,mList.get(i).getAudio_cover_id(),
                        mList.get(i).getAudio_id());
            }
        });
        if (SPUtils.isLogined()){
            loadData();
        }else {
            mList = queryAudios(mData);
            mAdapter.setList(mList);
        }
    }

    private void loadData() {
        String url = HttpConfig.USER_COVER_DETAIL;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("member_cover_id",mData.getId()+"");
        treeMap.put("page","-1");
        treeMap.put("pagesize","-1");
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.getInstance().postRxAndroidAES(url,treeMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseData>() {
                    @Override
                    public void accept(ResponseData responseData) throws Exception {
                        String code = responseData.getCode();
                        if (TextUtils.equals("200",code)){
                            String data = responseData.getData();
                            UserCoverDetailData userCoverDetailData = new Gson().fromJson(data, UserCoverDetailData.class);
                            mList = change(userCoverDetailData);
                            mAdapter.setList(mList);
                        }else{
                            ToastUtil.showShort(getContext(),"加载数据失败~");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.showShort(getContext(),"加载数据失败~");
                    }
                });

    }

    /**
     * /**
     * id : 音频id
     * title : 标题
     * url : url
     * duration : 时长
     * star : 点赞量
     * share : 分享量
     * collect : 收藏量
     * cover_id : 播单ID
     * cover_name : 播单名称
     *
     * @param userCenterData
     * @return
     */
    public List<DBFloatPlayListDetail> change(UserCoverDetailData userCenterData) {
        List<UserCoverDetailData.ListBean> list = userCenterData.getList();
        List<DBFloatPlayListDetail> mList = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            UserCoverDetailData.ListBean listBean = list.get(i);
            DBFloatPlayListDetail d = new DBFloatPlayListDetail();
//            d.setId(Long.valueOf(listBean.getId()));
            d.setAudio_title(listBean.getTitle());
            d.setAudio_cover_name(listBean.getCover_name());
            d.setAudio_cover_id(listBean.getCover_id());
            d.setAudio_url(listBean.getUrl());
            d.setAudio_id(listBean.getId());
            mList.add(d);
        }
        return mList;
    }

    private List<DBFloatPlayListDetail> queryAudios(DBFloatPlaylist data){
        //TODO 根据播放列表data，查询本地列表对应播单条目data
//        ArrayList<FloatPlayListDetailData> list = new ArrayList<>();
//        list.add(new FloatPlayListDetailData("0","人生如何悲喜并不重要，最重要的是我们拥有戏剧般的人生啊！", TestData.path1));
//        list.add(new FloatPlayListDetailData("0","想要一直爱着某物的话，以妖怪之死来说太长了；想要实现一切梦想的话，以人类之生来说太短了", TestData.path2));
//        list.add(new FloatPlayListDetailData("0","二营长，你他娘的意大利炮呢，给我拉出来看", TestData.path3));
//        list.add(new FloatPlayListDetailData("0","只有华丽并不是魔法，弹幕最重要的是火力", TestData.path4));
//        list.add(new FloatPlayListDetailData("0","daze", TestData.path5));
//        list.add(new FloatPlayListDetailData("0","二营长，你他娘的意大利炮呢，给我拉出来看", TestData.path6));
//        list.add(new FloatPlayListDetailData("0","这里可是我的城堡哦。要出去也该是你出去吧？", TestData.path7));
//        list.add(new FloatPlayListDetailData("0","我从未见过如此厚颜无耻之人", TestData.path8));

//        List<FloatPlayListDetailData> list = DBHelper.getInstance(mContext).queryAudiosByListId(data.get_id());
        List<DBFloatPlayListDetail> list = DBFloatPlayListDetailDaoHelp.queryBuilder(mContext,data.getId()+"");

        return list;
    }



    //刷新列表
    public void notifyList(DBFloatPlaylist data){
        if(mAdapter!=null){
            mData = data;
            mList = queryAudios(mData);
            mAdapter.setList(mList);
        }
    }
}
